package com.fyl.datasource.spring.boot.autoconfigure;

import com.fyl.datasource.context.DataSourceContextHolder;
import com.fyl.datasource.provider.DataSourceProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import java.util.Map;
import java.util.Objects;

public class DynamicDataSource extends AbstractRoutingDataSource {

    private static final Logger log = LoggerFactory.getLogger(DynamicDataSource.class);

    private String primary;

    private DataSourceProvider provider;

    @Override
    protected Object determineCurrentLookupKey() {
        return DataSourceContextHolder.getDataSourceKey();
    }

    @Override
    public void afterPropertiesSet() {
        Map<Object, Object> dataSources = provider.loadDataSources();
        if (Objects.isNull(dataSources.get(this.primary))) {
            throw new RuntimeException("dynamic-datasource Please check the setting of primary");
        }
        super.setTargetDataSources(dataSources);
        //设置默认数据源
        super.setDefaultTargetDataSource(dataSources.get(primary));
        super.afterPropertiesSet();
        log.info("dynamic-datasource initial loaded [{}] datasource,primary datasource named [{}]", dataSources.size(), this.primary);
    }

    public String getPrimary() {
        return primary;
    }

    public void setPrimary(String primary) {
        this.primary = primary;
    }

    public DataSourceProvider getProvider() {
        return provider;
    }

    public void setProvider(DataSourceProvider provider) {
        this.provider = provider;
    }
}
